<?php
class Ynadvsearch_Api_Search extends Core_Api_Abstract {
	
	public function getPaginator($text, $type = null) {
		$select = $this->getSelect($text, $type);
		return Zend_Paginator::factory($select);
	}
	
	public function getSelect($text, $type = null)
	{
		$table = Engine_Api::_()->getDbtable('search', 'core');
		$table_name = $table->info('name');

		$db = $table->getAdapter();
		$select = $table->select();
		
		$text = '%'.preg_replace('/\s+/', '%',$text).'%';
		
		if ($type) {
			
			$types = array();
			foreach ($type as $ty) {
				if ($ty) {
					$types = array_merge($types,$ty);
				}
			}
			if ($types) {
				$availableTypes = Engine_Api::_()->getItemTypes();
				$types = array_intersect($types,$availableTypes);
				$types = array_diff($types, array("groupbuy_category", "groupbuy_location","groupbuy_param","groupbuy_album","groupbuy_photo","music_playlist_song"));
				$types = "('". implode("','", $types). "')";
				$select->where("$table_name.type IN ".  $types);
				$select->where("$table_name.title like '$text' OR $table_name.description like '$text'");
			}
			else {
				
				return $select->where("$table_name.id < 0");
			}
		}
		else {
			return $select->where("$table_name.id < 0");
		}
		$select->order("$table_name.type");
		return $select;
	}
}